package cn.alex.sso.project.service.impl;

import cn.alex.sso.project.entity.SysRole;
import cn.alex.sso.project.entity.SysRoleClient;
import cn.alex.sso.project.mapper.SysRoleClientMapper;
import cn.alex.sso.project.mapper.SysRoleMapper;
import cn.alex.sso.project.service.SysRoleClientService;
import cn.alex.sso.project.sync.event.RoleAbstractDataSyncEvent;
import cn.alex.sso.project.sync.module.RoleDataSyncModule;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Alex
 * @description 针对表【sys_role_client(角色和应用关联表)】的数据库操作Service实现
 * @createDate 2024-09-24 18:43:57
 */
@Service
@RequiredArgsConstructor
public class SysRoleClientServiceImpl extends ServiceImpl<SysRoleClientMapper, SysRoleClient> implements SysRoleClientService {
    private final SysRoleMapper roleMapper;

    @Override
    public List<Long> getClientIdListByRoleId(List<Long> roleIdList) {
        List<SysRoleClient> roleClientList = baseMapper.selectList(new LambdaQueryWrapper<SysRoleClient>().in(SysRoleClient::getRoleId, roleIdList));
        if (CollUtil.isEmpty(roleClientList)) {
            return ListUtil.empty();
        }
        return roleClientList.stream().map(SysRoleClient::getClientId).collect(Collectors.toList());
    }

    @Override
    public void change(Long roleId, List<Long> clientIdList) {
        // 需要在授权前同步数据
        SpringUtil.getApplicationContext().publishEvent(new RoleAbstractDataSyncEvent(this, roleId, RoleDataSyncModule.Trigger.DELETE));
        baseMapper.delete(new LambdaQueryWrapper<SysRoleClient>()
                .eq(SysRoleClient::getRoleId, roleId)
        );

        if (CollUtil.isNotEmpty(clientIdList)) {
            clientIdList.forEach(clientId -> {
                baseMapper.insert(new SysRoleClient(roleId, clientId));
            });
        }

        // 在授权后再同步数据
        SysRole role = roleMapper.selectById(roleId);
        SpringUtil.getApplicationContext().publishEvent(new RoleAbstractDataSyncEvent(this, role, RoleDataSyncModule.Trigger.ADD));
    }

    @Override
    public void removeByRoleId(Long roleId) {
        baseMapper.delete(new LambdaQueryWrapper<SysRoleClient>()
                .eq(SysRoleClient::getRoleId, roleId)
        );
    }

    @Override
    public void removeByClientId(Long clientId) {
        baseMapper.delete(new LambdaQueryWrapper<SysRoleClient>()
                .eq(SysRoleClient::getClientId, clientId)
        );
    }
}




